﻿using System.Collections;
using System.Windows.Forms;


namespace EXEStart
{
    /// <summary>
    /// ListView列表排序接口
    /// </summary>
    public class ListViewColumnSorter : IComparer
    {
        /// <summary>
        /// 要排序的列编号
        /// </summary>
        public int SortColumn { set; get; } = 0;

        /// <summary>
        /// 排序方式
        /// </summary>
        public SortOrder OrderOfSort { set; get; }

        /// <summary>
        /// 比较两个对象，字符串忽略大小写
        /// </summary>
        private readonly CaseInsensitiveComparer ObjectCompare = new();

        /// <summary>
        /// 比较函数，不区分大小写
        /// </summary>
        /// <param name="x">比较对象x</param>
        /// <param name="y">比较对象y</param>
        /// <returns>相等返回0，x大于y返回负数，x小于y返回正数</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            if(int.TryParse(listviewX.SubItems[SortColumn].Text, out int _) &&
               int.TryParse(listviewY.SubItems[SortColumn].Text, out _))
            {
                compareResult = int.Parse(listviewX.SubItems[SortColumn].Text).CompareTo(int.Parse(listviewY.SubItems[SortColumn].Text));
            }
            else
            {
                compareResult = ObjectCompare.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text);
            }


            if(OrderOfSort == SortOrder.Ascending)
            {
                return compareResult;
            }
            else if(OrderOfSort == SortOrder.Descending)
            {
                return (-compareResult);
            }
            else
            {
                return 0;
            }
        }


    }

}
